package net.wanho.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.wanho.entity.ProductType;
import net.wanho.mapper.ProductTypeMapper;
import net.wanho.service.ProductTypeService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【product_type(商品分类表)】的数据库操作Service实现
* @createDate 2025-05-05 02:08:26
*/
@Service
@RequiredArgsConstructor
public class ProductTypeServiceImpl extends ServiceImpl<ProductTypeMapper, ProductType> implements ProductTypeService{

    @Override
    public List<ProductType> productCategoryTree() {
        List<ProductType> productTypeList = list();

        return productTypeList.stream()
                .filter(productType -> productType.getParentId() == 0)
                .peek(productType -> {
                    List<ProductType> children = findChildren(productTypeList, productType);
                    if(Objects.isNull(children)) {
                        children = new ArrayList<>();
                    }
                    productType.setChildProductCategory(children);
                })
                .collect(Collectors.toList());
    }

    @Override
    public void insertProductType(ProductType productType) {
        if(Objects.nonNull(lambdaQuery().eq(ProductType::getTypeName, productType.getTypeName()))) {
            throw new RuntimeException("分类名已存在！");
        }
        save(productType);
    }

    private List<ProductType> findChildren(List<ProductType> productTypeList, ProductType productType) {

        return productTypeList.stream()
                .filter(child -> child.getParentId().equals(productType.getTypeId()))
                .peek(child -> {
                    List<ProductType> children = findChildren(productTypeList, child);
                    if (Objects.isNull(children)) {
                        children = new ArrayList<>();
                    }
                    child.setChildProductCategory(children);
                })
                .collect(Collectors.toList());
    }
}




